<template>
  <div class="dept-heat-container">
    <h2>部门领用热度分析</h2>
    
    <div class="filter-bar">
      <el-date-picker
        v-model="dateRange"
        type="monthrange"
        range-separator="至"
        start-placeholder="开始月份"
        end-placeholder="结束月份"
        default-value="[new Date(new Date().getFullYear(), 0, 1), new Date()]"
        @change="handleDateChange"
      />
      <el-select v-model="assetTypeFilter" placeholder="选择资产类型">
        <el-option label="全部类型" value="" />
        <el-option label="电子设备" value="电子设备" />
        <el-option label="办公家具" value="办公家具" />
        <el-option label="车辆设备" value="车辆设备" />
        <el-option label="生产设备" value="生产设备" />
      </el-select>
      <el-button type="primary" @click="refreshData">刷新数据</el-button>
    </div>
    
    <div class="charts-section">
      <el-card class="chart-card">
        <template #header>
          <div class="card-header">
            <span>部门领用热力图</span>
          </div>
        </template>
        <div id="heatmapChart" class="chart"></div>
      </el-card>
      
      <el-card class="chart-card">
        <template #header>
          <div class="card-header">
            <span>部门领用趋势</span>
          </div>
        </template>
        <div id="trendChart" class="chart"></div>
      </el-card>
    </div>
    
    <div class="heat-ranking">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>部门领用排行榜</span>
          </div>
        </template>
        <el-table :data="rankingData" style="width: 100%" stripe border>
          <el-table-column type="index" label="排名" width="80" />
          <el-table-column prop="department" label="部门" width="150" />
          <el-table-column prop="borrowCount" label="领用次数" width="120" />
          <el-table-column prop="assetCount" label="资产数量" width="120" />
          <el-table-column prop="avgDuration" label="平均借用天数" width="150" />
          <el-table-column prop="hotScore" label="热度得分" width="120" />
        </el-table>
      </el-card>
    </div>
    
    <div class="recent-borrows">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>近期领用记录</span>
          </div>
        </template>
        <el-table :data="recentBorrows" style="width: 100%" stripe border>
          <el-table-column prop="assetName" label="资产名称" min-width="180" />
          <el-table-column prop="assetType" label="资产类型" width="120" />
          <el-table-column prop="borrowDept" label="借用部门" width="120" />
          <el-table-column prop="borrower" label="借用人" width="100" />
          <el-table-column prop="borrowDate" label="借用日期" width="150" />
          <el-table-column prop="returnDate" label="归还日期" width="150" />
          <el-table-column prop="status" label="状态" width="100" />
        </el-table>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import * as echarts from 'echarts'
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { selectInfoByCategoryAndDateAPI } from '@/api/asset.js'
import { ElMessage } from 'element-plus'

// ==================== 响应式数据 ====================
const dateRange = ref([
  new Date(new Date().getFullYear(), 0, 1),
  new Date()
]) // 日期筛选范围（默认全年）
const assetTypeFilter = ref('') // 资产类型筛选
const rankingData = ref([]) // 部门领用排行数据（后端返回）
const recentBorrows = ref([]) // 近期领用记录（后端返回）
// 图表实例（存储引用，非响应式）
const heatmapChart = ref(null)
const trendChart = ref(null)

// ==================== 核心：加载后端数据 ====================
const loadData = async () => {
  try {
    // 处理日期参数（格式化为 YYYY-MM-DD）
    const startDate = dateRange.value[0]?.toISOString().split('T')[0] || ''
    const endDate = dateRange.value[1]?.toISOString().split('T')[0] || ''

    // 调用后端接口，传入筛选条件
    const res = await selectInfoByCategoryAndDateAPI({
      assetCategory: assetTypeFilter.value, // 资产类型筛选（为空查所有）
      startDate: startDate, // 开始日期
      endDate: endDate // 结束日期
    })

    // 假设后端返回格式（根据实际接口调整字段名）
    if (res.code === 200 && res.data) {
      rankingData.value = res.data.rankingData || [] // 部门领用排行
      recentBorrows.value = res.data.recentBorrows || [] // 近期领用记录
      const heatmapData = res.data.heatmapData || [] // 热力图原始数据
      const trendData = res.data.trendData || [] // 趋势图原始数据

      // 数据加载后刷新图表
      initHeatmapChart(heatmapData)
      initTrendChart(trendData)
    } else {
      // 无数据时重置
      rankingData.value = []
      recentBorrows.value = []
      resetCharts()
      ElMessage.warning('暂无资产领用相关数据')
    }
  } catch (error) {
    console.error('加载资产领用数据失败：', error)
    rankingData.value = []
    recentBorrows.value = []
    resetCharts()
    ElMessage.error('数据加载失败，请重试')
  }
}

// ==================== 图表相关 ====================
// 初始化部门月度领用热力图
const initHeatmapChart = (heatmapData = []) => {
  const chartDom = document.getElementById('heatmapChart')
  if (!chartDom) return

  // 销毁旧实例，避免内存泄漏
  if (heatmapChart.value) {
    heatmapChart.value.dispose()
  }

  heatmapChart.value = echarts.init(chartDom)

  // 提取部门列表（从排行数据中获取）
  const departments = rankingData.value.map(item => item.department)
  const months = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']

  // 处理后端热力图数据（格式：[[月份索引, 部门索引, 领用次数], ...]）
  const formatHeatmapData = heatmapData.length > 0 
    ? heatmapData 
    : departments.flatMap((_, i) => 
        months.map((_, j) => [j, i, Math.floor(Math.random() * 20)])
      )

  const option = {
    tooltip: {
      position: 'top',
      formatter: params => {
        const month = months[params.value[0]]
        const dept = departments[params.value[1]]
        const count = params.value[2]
        return `${month} ${dept}: ${count}次`
      }
    },
    grid: {
      height: '50%',
      top: '10%',
      left: '8%',
      right: '5%'
    },
    xAxis: {
      type: 'category',
      data: months,
      splitArea: { show: true },
      axisLabel: { rotate: 30 }
    },
    yAxis: {
      type: 'category',
      data: departments.length > 0 ? departments : ['暂无部门'],
      splitArea: { show: true }
    },
    visualMap: {
      min: 0,
      max: 40,
      calculable: true,
      orient: 'horizontal',
      left: 'center',
      bottom: '15%',
      inRange: {
        color: ['#313695', '#4575b4', '#74add1', '#abd9e9', '#e0f3f8', '#ffffbf', '#fee090', '#fdae61', '#f46d43', '#d73027', '#a50026']
      }
    },
    series: [
      {
        name: '领用次数',
        type: 'heatmap',
        data: formatHeatmapData,
        label: { show: true, fontSize: 10 },
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ],
    // 无数据提示
    graphic: departments.length === 0 ? [{
      type: 'text',
      left: 'center',
      top: 'center',
      style: { text: '暂无数据', fontSize: 14, fill: '#999' }
    }] : []
  }

  heatmapChart.value.setOption(option)
}

// 初始化部门领用趋势折线图
const initTrendChart = (trendData = []) => {
  const chartDom = document.getElementById('trendChart')
  if (!chartDom) return

  // 销毁旧实例
  if (trendChart.value) {
    trendChart.value.dispose()
  }

  trendChart.value = echarts.init(chartDom)

  // 提取部门列表（默认取前4个热门部门）
  const hotDepartments = rankingData.value.slice(0, 4).map(item => item.department)
  const months = ['1月', '2月', '3月', '4月', '5月', '6月']

  // 处理后端趋势数据（格式：[{name: 部门名, data: [月度领用次数]}]）
  const formatTrendData = trendData.length > 0 
    ? trendData 
    : hotDepartments.map(dept => ({
        name: dept,
        type: 'line',
        data: months.map(() => Math.floor(Math.random() * 10) + 6),
        smooth: true
      }))

  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: '{b} <br/>{a}: {c}次'
    },
    legend: {
      data: hotDepartments.length > 0 ? hotDepartments : ['暂无部门'],
      top: 0
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: months
    },
    yAxis: {
      type: 'value',
      min: 0,
      axisLabel: { formatter: '{value}次' }
    },
    series: formatTrendData.length > 0 ? formatTrendData : [
      { name: '暂无数据', type: 'line', data: [], smooth: true }
    ],
    // 无数据提示
    graphic: hotDepartments.length === 0 ? [{
      type: 'text',
      left: 'center',
      top: 'center',
      style: { text: '暂无趋势数据', fontSize: 14, fill: '#999' }
    }] : []
  }

  trendChart.value.setOption(option)
}

// 重置图表为无数据状态
const resetCharts = () => {
  initHeatmapChart([])
  initTrendChart([])
}

// 图表自适应窗口大小
const handleResize = () => {
  heatmapChart.value && heatmapChart.value.resize()
  trendChart.value && trendChart.value.resize()
}

// ==================== 交互方法 ====================
// 日期筛选变化
const handleDateChange = () => {
  refreshData()
}

// 资产类型筛选变化（需在模板的 el-select 上绑定 @change="handleFilterChange"）
const handleFilterChange = () => {
  refreshData()
}

// 刷新数据（筛选条件变化时调用）
const refreshData = () => {
  console.log('刷新数据：', {
    dateRange: dateRange.value,
    assetTypeFilter: assetTypeFilter.value
  })
  loadData() // 重新调用接口加载数据
}

// ==================== 生命周期 ====================
// 组件挂载时加载初始数据
onMounted(() => {
  loadData()
  window.addEventListener('resize', handleResize)
})

// 组件卸载时销毁图表+移除事件
onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)
  heatmapChart.value && heatmapChart.value.dispose()
  trendChart.value && trendChart.value.dispose()
})
</script>

<style scoped>
.dept-heat-container {
  padding: 20px;
}

.filter-bar {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
  flex-wrap: wrap;
  align-items: center;
}

.charts-section {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.chart-card {
  height: 400px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart {
  width: 100%;
  height: 320px;
}

.heat-ranking {
  margin-bottom: 30px;
}

.recent-borrows {
  margin-top: 30px;
}
</style>